import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, EntityManager } from 'typeorm';
import { Order } from './order.entity';
import { CreateOrderDto } from './dto/create-order.dto';
import { User } from '../user/user.entity';
import { Product } from '../product/product.entity';
import { InjectEntityManager } from '@nestjs/typeorm';
import { InjectQueue } from '@nestjs/bull';
import { Queue } from 'bull';

@Injectable()
export class OrderService {
  constructor(
    @InjectRepository(Order)
    private readonly orderRepository: Repository<Order>,
    @InjectRepository(Product)
    private readonly productRepository: Repository<Product>,
    @InjectEntityManager()
    private readonly entityManager: EntityManager,
    @InjectQueue('order')
    private readonly orderQueue: Queue,
  ) {}

  async create(user: User, dto: CreateOrderDto): Promise<Order> {
    const order = await this.entityManager.transaction(async manager => {
      const product = await manager.findOne(Product, { where: { id: dto.productId } });
      if (!product) throw new NotFoundException('商品不存在');
      if (product.stock < dto.quantity) throw new BadRequestException('库存不足');
      // 扣减库存
      product.stock -= dto.quantity;
      await manager.save(product);
      // 创建订单
      const order = manager.create(Order, {
        user,
        product,
        quantity: dto.quantity,
        totalPrice: Number(product.price) * dto.quantity,
        status: 'pending',
      });
      return manager.save(order);
    });
    // 下单后推送到队列，30分钟后自动取消未支付订单
    await this.orderQueue.add('auto-cancel', { orderId: order.id }, { delay: 30 * 60 * 1000 });
    return order;
  }

  async findAll(user: User): Promise<Order[]> {
    return this.orderRepository.find({ where: { user: { id: user.id } }, relations: ['product'] });
  }

  async findOne(user: User, id: number): Promise<Order> {
    const order = await this.orderRepository.findOne({ where: { id, user: { id: user.id } }, relations: ['product'] });
    if (!order) throw new NotFoundException('订单不存在');
    return order;
  }

  async findAllForAdmin(): Promise<Order[]> {
    return this.orderRepository.find({ relations: ['user', 'product'] });
  }

  async findOneForAdmin(id: number): Promise<Order> {
    const order = await this.orderRepository.findOne({ where: { id }, relations: ['user', 'product'] });
    if (!order) throw new NotFoundException('订单不存在');
    return order;
  }

  async removeForAdmin(id: number): Promise<void> {
    await this.orderRepository.delete(id);
  }
}
